package cn.rui.websocket;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.rui.mapper.UserMapper;
import cn.rui.pojo.User;
import cn.rui.pojo.vo.ChatBean;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/websocket/{userName}")
//此注解相当于设置访问URL
public class WebSocketServer {

    private Session session;

    private static UserMapper userMapper;

    @Autowired
    public void setDeviceListenerService(UserMapper userMapper) {
        WebSocketServer.userMapper = userMapper;
    }


    private static CopyOnWriteArraySet<WebSocketServer> webSockets = new CopyOnWriteArraySet<> ();
    private static Map<String, Session> sessionPool = new HashMap<String, Session> ();

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userName") String userName) {
        this.session = session;
        webSockets.add (this);
        sessionPool.put (userName, session);

        //在线信息发送到前台
        if (sessionPool.size () != 0) {
            Set<String> strings = sessionPool.keySet ();
            ChatBean chatBean = new ChatBean ();

            Set<String> realNames = new HashSet<> ();
            for (String string : strings) {
                QueryWrapper<User> wrapper = new QueryWrapper<> ();
                wrapper.eq ("username", string);
                User user = userMapper.selectOne (wrapper);
                realNames.add (user.getRealName ());
            }

            chatBean.setStatus (2);
            chatBean.setOnlineName (realNames);
            JSONObject json = JSONUtil.parseObj (chatBean, false, true);
            sendAllMessage (json.toStringPretty ());
        }

        //System.out.println (userName + "【websocket消息】有新的连接，总数为:" + webSockets.size ());
    }

    @OnClose
    public void onClose(@PathParam(value = "userName") String userName) {
        sessionPool.remove (userName);
        webSockets.remove (this);

        //在线信息发送到前台
        //在线信息发送到前台
        if (sessionPool.size () != 0) {
            Set<String> strings = sessionPool.keySet ();
            ChatBean chatBean = new ChatBean ();

            Set<String> realNames = new HashSet<> ();
            for (String string : strings) {
                QueryWrapper<User> wrapper = new QueryWrapper<> ();
                wrapper.eq ("username", string);
                User user = userMapper.selectOne (wrapper);
                realNames.add (user.getRealName ());
            }

            chatBean.setStatus (2);
            chatBean.setOnlineName (realNames);
            JSONObject json = JSONUtil.parseObj (chatBean, false, true);
            sendAllMessage (json.toStringPretty ());
        }

        //System.out.println ("【websocket消息】连接断开，总数为:" + webSockets.size ());
    }

    @OnMessage
    public void onMessage(String message) {
        //System.out.println ("【websocket消息】收到客户端消息:" + message);
    }

    // 此为广播消息
    public void sendAllMessage(String message) {
        for (WebSocketServer webSocket : webSockets) {
            //System.out.println ("【websocket消息】广播消息:" + message);
            try {
                webSocket.session.getAsyncRemote ().sendText (message);
            } catch (Exception e) {
                e.printStackTrace ();
            }
        }
    }

    // 此为单点消息
    public void sendOneMessage(String userName, String message) {
        //System.out.println ("【websocket消息】单点消息:" + message);
        Session session = sessionPool.get (userName);
        if (session != null) {
            try {
                session.getAsyncRemote ().sendText (message);
            } catch (Exception e) {
                e.printStackTrace ();
            }
        }
    }
}